package com.application.fabric.users.config.encryptAl;

import org.springframework.stereotype.Repository;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

@Repository
public class Hashencry {
    public String hash(String key , String msg) throws Exception {
        return encrypt("HmacMD5",key,msg);
    }
    public static String encrypt(String algorithm, String key, String message) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
        Mac mac = Mac.getInstance(algorithm);
        mac.init(secretKeySpec);
        byte[] digest = mac.doFinal(message.getBytes("UTF-8"));
        return byte2hex(digest);
    }

    private static String byte2hex(byte[] bytes) {
        StringBuilder builder = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            tmp = Integer.toHexString(b & 0xFF);
            if (tmp.length() == 1) {
                builder.append("0");
            }
            builder.append(tmp);
        }
        return builder.toString();
    }
}
